from re import findall
from flask import Blueprint,request,jsonify
import json
from db import db1
from werkzeug.security import check_password_hash,generate_password_hash
bp_auser = Blueprint('auser',__name__)

@bp_auser.route('/reg',methods=['POST'])
def reg():
    password = generate_password_hash('123456')
    sql = "insert into auser values(0,'15947159146','%s','二手房色鬼生日歌是个个帅哥')"%(password)
    db1.insert(sql)
    return 'ok'

@bp_auser.route('/login',methods=['POST'])
def login():
    data= request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = "select * from auser where username='%s'"%(data['username'])
    res = db1.findone(sql)
    if res:
        if check_password_hash(res['password'],data['password']):
            return jsonify({'code':200,'userid':res['id'],'username':res['username']})
        else:
            return jsonify({'code':10010,'mes':'密码错误'})
    return jsonify({'code':200,'mes':'用户不存在'})

@bp_auser.route('/articleM',methods=['POST','GET'])
def article():
    if request.method=='POST':
        data= request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "insert into article(title,content,userid) values('%s','%s',%d)"%(data['title'],data['content'],int(data['userid']))
        db1.insert(sql)
        return jsonify({'code':200})
    else:
        uid = int(request.args.get('uid'))
        if uid>0:
            sql = "select * from article where userid=%d"%(uid)
        else:
            sql = "select * from article"
        res = db1.findall(sql)
        return jsonify({'code':200,'list':res})
    
